package com.rp.news.exception;

import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandle {


    @ExceptionHandler(MyCustomExeption.class)
    @ResponseBody
    public Result graceException(MyCustomExeption e) {
        //e.printStackTrace();
        log.info("自定义异常"+e.getResponseStatusEnum().status() + ";原因:" + e.getResponseStatusEnum().msg());
        return Result.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result graceException(Exception e) {
        log.info("异常:{}",e.getMessage());
        return new Result(ResponseStatusEnum.SYSTEM_ERROR,e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result graceException(MethodArgumentNotValidException e) {
        log.info("参数异常:{}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errors = getErrors(bindingResult);
        return Result.errorMap(errors);
    }

    public Map<String,String> getErrors(BindingResult bindResult){
        Map<String,String> map = new HashMap<>();
        List<FieldError> fieldErrors = bindResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return map;
    }

}
